import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: { requiresAuth: false },
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/HomeView.vue'),
      meta: { requiresAuth: true },
      children: [
        {
          path: 'welcome',
          name: 'welcome',
          component: () => import('@/views/WelcomeView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'disaster-report',
          name: 'disaster-report',
          component: () => import('@/views/guest/DisasterReportView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'disaster-view',
          name: 'disaster-view',
          component: () => import('@/views/guest/DisasterView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'disaster-intro',
          name: 'disaster-intro',
          component: () => import('@/views/guest/DisasterIntroView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'map-view',
          name: 'map-view',
          component: () => import('@/views/admin/MapView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'disaster-confirm',
          name: 'disaster-confirm',
          component: () => import('@/views/admin/DisasterConfirmView.vue'),
          meta: { requiresAuth: true },
        },
        {
          path: 'disaster-analysis',
          name: 'disaster-analysis',
          component: () => import('@/views/admin/DisasterAnalysisView.vue'),
          meta: { requiresAuth: true },
        },
      ],
    },
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login',
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)

  // 如果需要登录但用户未登录，重定向到登录页
  if (requiresAuth && !userStore.isLoggedIn()) {
    next('/login')
  }
  // 如果已登录且访问登录页，重定向到首页
  else if (userStore.isLoggedIn() && to.path === '/login') {
    next('/home/welcome')
  } else {
    next()
  }
})

export default router
